'use strict'

class content {

  constructor () {
    //param默认就是/:id，若要改变路由，则可以设置此属性，比如设置为/:name
    //this.param = '/:id'
  }
  __mid(){
    return[
      {
        name:'token-verify',
        path:['post','delete']
      }
    ]
  }

  //以下方法，若不需要，要去掉，避免无意义的路由。

  //获取资源具体内容
  //对应路由 GET/concent/:id
  async get (c) {
    let id = c.param.id
    let sqltext = 'SELECT id,detail,title,update_time'
    +' FROM content WHERE id=$1';
    let r = await c.service.psql.query(sqltext,[id])
    if(r.rowCount === 0 ){
        return c.status(404).send('not found');
    }
    c.send(r.rows[0])
    

  }

  //创建资源
  //对应路由 POST/concent/:id
  async post (c) {
    try{
      // c.body是提交的请求数据。
      let data =  JSON.parse(c.body)
      let sqltext = 'INSERT INTO content'
       +'(id,detail,title,add_time,update_time)'
       +'VALUES($1,$2,$3,$4,$5)'
       
      // 随机数转换成16进制字符串并去掉前两位，字串作为ID
       let id = Math.random().toString(16).substring(2)
       let tm = Date.now()
       let r = await c.service.psql.query(sqltext,[
          id,data.detail,data.title,tm,tm

       ])
       if(r.rowCount===0){
           return c.status(500).send('failed')
       }
       c.send(id)
  }catch(err){
      console.error(err)
      c.status(400).send('bad data')
  }

  }

  //更新资源
  //对应路由 PUT/concent/:id
  async put (c) {

  }

  //获取列表
  //对应路由 GET/concent/
  async list (c) {
    let sqltext = 'SELECT id,title,update_time FROM content'
    let r = await c.service.psql.query(sqltext)
    c.send(r.rows)

  }

  //删除资源
  //对应路由 DELECT/concent/:id
  async delete (c) {
    let r = await c.service.psql.query(`DELETE FROM content WHERE id=$1`, 
        [ c.param.id ]
      )
    c.send({
      count: r.rowCount
    })
}

}

module.exports = content
